package com.star.system.controller;

import com.star.system.aspect.RequestLog;
import com.star.system.aspect.Type;
import com.star.system.dto.LoginDTO;
import com.star.system.service.CaptchaService;
import com.star.security.authentication.AuthenticationService;
import com.star.security.authentication.usernamepassword.UsernamePasswordAuthenticationToken;
import com.star.security.authentication.wxapp.WxappAuthenticationToken;
import com.star.security.context.ResponseToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 登录
 *
 * @author yangzj
 * @order 1
 */
@RestController
public class LoginController {
    @Resource
    private AuthenticationService authenticationService;
    @Autowired
    private CaptchaService captchaService;
    @Value("${security.is-captcha}")
    private Boolean isCaptcha;
    @Value("${security.expires-in}")
    private Long expiresIn;
    @Value("${security.wxapp.expires-in}")
    private Long wxappExpiresIn;

    /**
     * 登录（直接写入cookie）
     *
     * @param dto      入参
     * @param response 响应
     */
    @RequestLog(Type.LOGIN)
    @PostMapping("/login")
    public void login(@Valid @RequestBody LoginDTO dto, HttpServletResponse response) {
        if (isCaptcha) {
            captchaService.verify(dto.getUuid(), dto.getCaptcha());
        }
        ResponseToken res = authenticationService.login(
                UsernamePasswordAuthenticationToken.unauthenticated(dto.getUsername(), dto.getPassword(), dto.getType(), expiresIn, true));
        res.setCookie(response);
    }

    /**
     * 微信小程序登录
     *
     * @param code code
     * @param type 类型 1小程序用户端 2小程序导师端
     * @return {@link ResponseToken}
     */
    @RequestLog(Type.LOGIN)
    @GetMapping("/wxapp-login")
    public ResponseToken wxappLogin(@RequestParam("code") String code, @RequestParam("type") Integer type) {
        return authenticationService.login(
                WxappAuthenticationToken.unauthenticated(code, type, wxappExpiresIn));
    }

    /**
     * 注销-通用
     *
     * @param request HttpServletRequest
     */
    @GetMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response){
        authenticationService.logout(request);
        ResponseToken.removeCookie(request, response);
    }

    /**
     * 获取验证码
     *
     * @param uuid     uuid
     * @param width    宽度
     * @param height   高度
     * @param response 响应
     */
    @GetMapping("/captcha")
    public void getCaptcha(@RequestParam String uuid, @RequestParam int width, @RequestParam int height
            , HttpServletResponse response) {
        captchaService.create(uuid, width, height, response);
    }
}
